
/**   
*    
* 项目名称：a_yongan   
* 类名称：OutsourcingInServiceImpl   
* 类描述：   
* 创建人：liubo   
* 创建时间：2018年6月30日 上午10:59:50    
* 修改时间：2018年6月30日 上午10:59:50   
* 修改备注：   
* @version    
*    
*/
package com.yongan.sales.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import com.yongan.sales.dao.SalesOrderDao;
import com.yongan.sales.dao.SalesOrderDetailsDao;
import com.yongan.sales.dao.SalesOutDao;
import com.yongan.sales.entity.SalesOrderDetails;
import com.yongan.sales.entity.SalesOut;
import com.yongan.sales.service.SalesOutService;
import com.yongan.user.enums.UserStatEnum;
import com.yongan.user.exception.UserException;
import com.yongan.util.Execution;
import com.yongan.warehouse.dao.GoodsinformationDao;

/**
 * @author liubo
 *
 */
@Service
public class SalesOutServiceImpl implements SalesOutService{

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private SalesOrderDao salesOrderDao;
	@Autowired
	private SalesOutDao salesOutDao;
	@Autowired
	private SalesOrderDetailsDao detailsDao;
	@Autowired
	private GoodsinformationDao goodsinformationDao;
	private final String slat = "dsjdajsdkHJJHAJAKdsd921e0p12*DAe#@$@!qew";
	@Override
	public List<SalesOut> getSalesOutList(int offset, int limit) {
		return salesOutDao.queryAll(offset, limit);
	}

	
	@Override
	public SalesOut getSalesOutById(String salesOutId) {
		// TODO 自动生成的方法存根
		SalesOut salesOut = salesOutDao.queryById(salesOutId);
		salesOut.setDetails(detailsDao.queryAllByTopId(salesOut.getSalesOutSpddId()));
		salesOut.setSalesOrder(salesOrderDao.queryById(salesOut.getSalesOutSpddId()));
		return salesOut;
	}

	

	@Override
	@Transactional
	public Execution executeSalesOut(SalesOut salesOut,
			String salesOutId, String md5) throws UserException {
		if(md5 == null || !md5.equals(getMD5(salesOutId))){
			//throw new UserException("user data rewrite");
		}
		List<SalesOrderDetails> details =null;
		try{
			Boolean updateDetailsRkslIs = false;
			if(salesOut == null){//删除
				SalesOut readDell = salesOutDao.queryById(salesOutId);
				details = detailsDao.queryAllByTopId(readDell.getSalesOutSpddId());
				//details = readDell.getDetails();
				if(!(details==null)){
					for(SalesOrderDetails goodDetails:details){
						//首先将detail中的入库数量滞空
						int updateDetailsRksl = detailsDao.updateDetailsCksl(goodDetails.getSalesOrderDetailsId(),"");
						if(updateDetailsRksl<=0){
							updateDetailsRkslIs = true;//标识滞空detail中的入库数量失败
						}
						//其次，减去商品中已新增的数量
						reduceNumber(goodDetails, "add");
					}
				}
				//更改采购订单中可选择的标识
				int changeCount = salesOrderDao.isChecked(readDell.getSalesOutSpddId(),"false");
				//删除采购入库单
				int deleteCount = salesOutDao.deleteSalesOut(salesOutId);
				
				if(deleteCount<=0 & changeCount<=0 & updateDetailsRkslIs){
					throw new UserException("delete failed");
				}else{
					return new Execution(salesOutId, UserStatEnum.SUCCESS);
				}
			}else if((salesOutId.equals(""))){//新增
				details = salesOut.getDetails();
				int goodDetailsaddcount = 1;
				if(!(details==null)){
					for(SalesOrderDetails goodDetails:details){
						//System.out.println(goodDetails.getpurchasegoodsdetailsId()+"==="+goodDetails.getPurchasegoodsdetailsRksl());
						int updateDetailsCksl = detailsDao.updateDetailsCksl(goodDetails.getSalesOrderDetailsId(),goodDetails.getSalesOrderDetailsCksl());
						if(updateDetailsCksl<=0){
							updateDetailsRkslIs = true;//标识滞空detail中的入库数量失败
						}
						reduceNumber(goodDetails, "reduce");
					}
				}
				int changeCount = salesOrderDao.isChecked(salesOut.getSalesOutSpddId(),"true");
				int addCount = salesOutDao.insertSalesOut(salesOut);
				if(addCount<=0 & goodDetailsaddcount<=0 & updateDetailsRkslIs & changeCount<=0){
					throw new UserException("add failed");
				}else{
					return new Execution(salesOut.getSalesOutId(), UserStatEnum.SUCCESS);
				}
			}else if(!(salesOutId.equals(""))){//修改
				List<SalesOrderDetails> oldList = detailsDao.queryAllByTopId(salesOut.getSalesOutSpddId());
			//	List<String> newList = new ArrayList<String>();
				//String[] newList;
				details = salesOut.getDetails();
				if (oldList != null) {
					for (SalesOrderDetails old : oldList) {
						// 减去旧列表在库存中的数量
						reduceNumber(old, "add");
					}
				}
				//int goodDetailscount = 1;
				if(!(details==null)){
					for(SalesOrderDetails goodDetails:details){
						int updateDetailsCksl = detailsDao.updateDetailsCksl(goodDetails.getSalesOrderDetailsId(),goodDetails.getSalesOrderDetailsCksl());
						if(updateDetailsCksl<=0){
							updateDetailsRkslIs = true;//标识滞空detail中的入库数量失败
						}
						//加上新保存的列表
						reduceNumber(goodDetails, "reduce");
					}
				}

				int updateCount = salesOutDao.updateSalesOut(salesOut);
				if(updateCount<=0 & updateDetailsRkslIs){
					throw new UserException("update failed");
				}else{
					return new Execution(salesOutId, UserStatEnum.SUCCESS);
				}
			}else{
				throw new UserException("parameter error");
			}
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			throw new UserException("inner error:"+e.getMessage());
		}
	}

	
	@Override
	public int getCount() {
		// TODO 自动生成的方法存根
		return salesOutDao.queryCount();
	}
	
	private String getMD5(String Id){
		String base = Id + "/" + slat;
		String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
		return md5;
	}


	public SalesOutServiceImpl() {
		super();
		// TODO 自动生成的构造函数存根
	}


	public int reduceNumber(SalesOrderDetails igd,  String type){
		return goodsinformationDao.reduceNumber(igd.getSalesOrderDetailsHpbm()
				, type, Integer.parseInt(igd.getSalesOrderDetailsHpsl())
				, Integer.parseInt(igd.getSalesOrderDetailsCksl()));
	}

}
